package com.gitee.mp.core.mapper;

import cn.hutool.core.util.ArrayUtil;
import com.gitee.mp.configure.MilvusConfigure;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

/**
 * 动态注册 Mapper 代理类至 Spring 容器中
 *
 * @author hongda.li
 */
@Component
public class MilvusMapperRegistry implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware {

    private ApplicationContext context;

    @Override
    public void setApplicationContext(@NonNull ApplicationContext context) throws BeansException {
        this.context = context;
    }

    @Override
    public void postProcessBeanDefinitionRegistry(@NonNull BeanDefinitionRegistry registry) throws BeansException {
        // Mapper工厂
        MilvusMapperFactory factory = this.context.getBean(MilvusMapperFactory.class);

        // Milvus配置项
        MilvusConfigure configure = factory.getConnectorFactory().getConfigure();

        // Mapper扫描器
        MilvusMapperScanner scanner = new MilvusMapperScanner(registry, factory);

        // 扫描指定包路径下的Mapper
        scanner.doScan(ArrayUtil.toArray(configure.getLocationList(), String.class));
    }
}
